<template>
  <view class="bg-grey pad20">
    <sb-back-icon></sb-back-icon>
    <scroll-view>
      <u-cell-group
        :title="defaultAddress.region"
        class="address-info bg-white radius16 pad20 shadow-line"
        :border="false"
      >
        <u-cell-item
          center
          :title="defaultAddress.address || '请添加收货信息'"
          :border-bottom="false"
          :is-link="true"
          :label="defaultAddress.name + '   ' + defaultAddress.tel"
          ndex="index"
          @click="goAddress"
        >
        </u-cell-item>
      </u-cell-group>
      <u-gap height="30" bgColor="#f4f8f9"></u-gap>
      <view class="bg-white radius16 pad20 shadow-line">
        <view
          class="order-info flex bg-white pad10"
          v-for="item in order.orderInfo"
          :key="item.id"
        >
          <u-image
            class="marh10"
            :src="item.sku.cover"
            width="150rpx"
            height="150rpx"
            border-radius="10rpx"
          />
          <view class="item-info h100 flex1 flex flex-col j-s">
            <view class="title u-line-2">
              {{ item.name || item.sku.goods.name }}
            </view>
            <view class="sku-spec font24">
              {{ item.skuSpec }}
            </view>
            <view>
              <view class="flex j-s">
                <view class="c-price">
                  <span
                    >￥<span class="number u-font-16">{{
                      item.sku.salePrice
                    }}</span></span
                  >
                </view>
                <u-number-box
                  :min="1"
                  v-model="item.sku.count"
                  @change="changeCount(item)"
                ></u-number-box>
              </view>
            </view>
          </view>
        </view>
      </view>
      <u-gap height="30" bgColor="#f4f8f9"></u-gap>
      <u-cell-group :border="false" class="bg-white radius16 pad20 shadow-line">
        <u-cell-item title="商品金额" :arrow="false">
          <view slot="right-icon" class="w100 goods-price">
            ￥{{ orderPrice.originalPrice }}
          </view>
        </u-cell-item>
        <u-cell-item
          title="优惠券"
          @click="
            $go2(
              `/pages/main/tabbar/mine/discount-coupon?id=${order.orderInfo[0].id}`
            )
          "
          :arrow="!discountCoupon.tk"
        >
          <view
            v-if="discountCoupon.tk"
            slot="right-icon"
            class="w100 goods-price"
          >
            已减免￥{{ orderPrice.reducePrice || "" }}元
          </view>
        </u-cell-item>
        <u-cell-item
          class="remark-cell"
          title="备注"
          :arrow="false"
          :clickable="false"
        >
          <u-input
            type="textarea"
            slot="right-icon"
            v-model="remark"
            placeholder="请输入备注"
            :autosize="{ minHeight: 20 }"
          ></u-input>
        </u-cell-item>
      </u-cell-group>
      <view class="submit-content bg-white footer flex j-s a-c w100 padh30">
        <view class="c-price flex a-c">
          <span
            >￥<span class="number font42">{{
              orderPrice.presentPrice
            }}</span></span
          >
        </view>
        <view class="submit-btn">
          <u-button type="error" shape="circle" @click="submitOrder"
            >Confirm</u-button
          >
        </view>
      </view>
    </scroll-view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { OrderState } from "../../../core/constant.js";
export default {
  onLoad() {
    if (!this.$checkLogin()) return this.$redirect2Login();
    this.getOrderDetail();
    this.setPrice();
  },
  onShow() {
    this.defaultAddress = this.order.orderAddress;
    console.log(this.defaultAddress);
    if (!this.order?.orderInfo?.length)
      this.$go2(`/pages/main/order/order-info?id=${this.orderId}`);
  },
  data() {
    return {
      info: {
        state: 1,
      },
      defaultAddress: {},
      id: "",
      cata_id: 0,
      res: "",
      remark: "",
      discountCoupon: {},
      orderPrice: {
        originalPrice: 0,
        presentPrice: 0,
        reducePrice: 0,
      },
    };
  },
  computed: {
    ...mapState(["order"]),
  },
  watch: {
    "discountCoupon.tk"() {
      this.setPrice();
    },
  },
  methods: {
    ...mapMutations(["SET_ORDER_INFO", "SET_ADDRESS"]),
    setPrice() {
      //originalPrice  应付   reducePrice优惠  presentPrice  实付
      let { originalPrice, presentPrice, reducePrice } = this.orderPrice;
      originalPrice = this.order.orderInfo.reduce((total, item) => {
        total += item.price;
        return total;
      }, 0);
      if (this.discountCoupon.tk) {
        const tk = this.discountCoupon.tk;
        switch (tk.type) {
          case 1: //满减
          // let [goal, reduce] = tk.desc.split("-").map(parseFloat);
          // if (goal < price) throw "未满足优惠券使用条件";
          // tk_reduce = reduce;
          // break;
          case 2: //直减
            presentPrice =
              parseFloat(originalPrice) -
              parseFloat(this.discountCoupon.tk.reduce);
            break;
          case 3: //打折
            presentPrice = (parseFloat(tk.discount) / 10) * originalPrice;
        }
      } else {
        presentPrice = originalPrice;
      }
      presentPrice = presentPrice > 0 ? presentPrice : 0;
      reducePrice = (originalPrice - presentPrice).toFixed(2);
      this.orderPrice = { originalPrice, presentPrice, reducePrice };
      console.log(this.orderPrice);
    },
    goAddress() {
      // if (this.unPayed)
      this.$go2("/pages/main/address/list?fromOrder=1");
    },
    async submitOrder() {
      if (!this.defaultAddress.address) {
        this.$msg("请先添加收货信息");
        return;
      }
      console.log(this.defaultAddress);
      try {
        let { success, data } = await this.$postB("/order/add", {
          createdBy: this.defaultAddress.createdBy,
          remark: this.remark,
          originalPrice: this.orderPrice.originalPrice,
          presentPrice: this.orderPrice.presentPrice,
          reducePrice: this.orderPrice.reducePrice,
          receiver: this.defaultAddress.name,
          tel: this.defaultAddress.tel,
          address: this.defaultAddress.address,
          region: this.defaultAddress.region,
          ticketFlowId: this.discountCoupon?.id,
          skus: this.order.orderInfo.map((i) => {
            return { skuId: i.sku.id, count: i.count || i.sku.count };
          }),
        });
        console.log(this.order.orderInfo);
        if (data) this.orderId = data;
        if (success) {
          const fromCart = this.order.orderInfo.find((o) => o.fromCart);
          if (fromCart) {
            const fromCartList = this.order.orderInfo
              .filter((o) => o.fromCart)
              .map((m) => m.id);
            await this.$postB("/cart/del", {
              id: fromCartList,
            });
          }
          this.SET_ORDER_INFO([]);
          console.log(this.order.orderInfo);
          this.$go2(`./add-success?id=${data}`);
        } else this.$msg(data);
      } catch (e) {
        this.$refs.uToast.show({
          title: "订单提交失败",
          type: "error",
        });
      }
    },
    async getOrderDetail() {
      let { success, data } = await this.$get("/cus-address/first");
      if (success && data) {
        this.defaultAddress = data;
        this.SET_ADDRESS(data);
      } else this.defaultAddress = this.order.orderAddress;
      console.log(this.order.orderAddress);
    },
    changeCount(item) {
      item.price = item.sku.salePrice * item.sku.count;
      this.setPrice();
    },
  },
};
</script>

<style lang="scss" scoped>
.address-info {
  background: white;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  .pay {
    background: #e2231a;
    border-radius: 40rpx;
    color: #fff;
  }
}
.order-info {
  height: 200rpx;
  .item-info {
    .title {
      line-height: normal;
    }
    .sku-spec {
      color: #bbb;
    }
    .demo-tag-owner {
      background-color: #c33;
      color: #ffffff;
      display: flex;
      align-items: center;
      padding: 4rpx 14rpx;
      border-radius: 50rpx;
      font-size: 20rpx;
      line-height: 1;
    }

    .demo-tag-text {
      border: 1px solid #c33;
      color: #c33;
      margin-left: 10px;
      border-radius: 50rpx;
      line-height: 1;
      padding: 4rpx 14rpx;
      display: flex;
      align-items: center;
      border-radius: 50rpx;
      font-size: 20rpx;
    }
  }
}
.submit-content {
  height: 100rpx;
  .submit-btn {
    width: 150rpx;
  }
}
.remark-cell {
  /deep/ .u-cell__value {
    flex: 0;
  }
  /deep/ .u-cell_right {
    margin-left: 20rpx;
    flex: 1;
  }
  .goods-price {
    text-align: right;
  }
}
</style>
